<template>
  <div class="online-users-card">
    <div class="card-title">实时在线用户数量</div>
    <div class="user-count">{{ dashboardStore.onlineUsers }}</div>
    <div class="update-time">更新时间: {{ currentTime }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useDashboardStore } from '../stores/dashboard';

const dashboardStore = useDashboardStore();
const currentTime = ref(formatTime(new Date()));
let timer = null;

// 格式化时间
function formatTime(date) {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
}

// 定时更新数据
onMounted(() => {
  // 初始更新
  dashboardStore.updateOnlineUsers();
  
  // 设置定时器，每10秒更新一次
  timer = setInterval(() => {
    dashboardStore.updateOnlineUsers();
    currentTime.value = formatTime(new Date());
  }, 10000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
.online-users-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
  height: 100%;
}

.card-title {
  font-size: 22px;
  margin-bottom: 24px;
}
.user-count {
  font-size: 60px;
  margin-bottom: 18px;
}
.update-time {
  font-size: 16px;
}
</style>